package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Jqcc
 * @Version 1.0
 * @Data 2023/8/12
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;


    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    @Override
    public List<AddressBook> list() {

        Long userId = BaseContext.getCurrentId();

        List<AddressBook> addressBookByUserId = addressBookMapper.getAddressBookByUserId(userId);

        return addressBookByUserId;
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void addAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询默认地址
     *
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        Long userId = BaseContext.getCurrentId();

        AddressBook addressBook = addressBookMapper.getDefaultAddressByUserId(userId);

        return addressBook;
    }

    /**
     * 设置默认地址
     *
     * @param id
     */
    @Override
    public void setDefaultAddress(Long id) {
        Long userId = BaseContext.getCurrentId();

        //先更改原有的默认地址
        addressBookMapper.updateDefaultAddressByUserId(userId);

        // 设置默认地址
        addressBookMapper.setDefaultAddressByUserId(userId, id);
    }


    /**
     * 根据id修改地址
     * @param addressBook
     */
    @Override
    public void updateAddress(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();

        addressBook.setUserId(userId);

        addressBookMapper.updateById(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressById(Long id) {

        AddressBook addressBook = addressBookMapper.getAddressById(id);
        return addressBook;
    }


    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteAddress(Long id) {
        Long userId = BaseContext.getCurrentId();
        addressBookMapper.deleteAddressById(id, userId);
    }
}
